from rest_framework import serializers
from .models import User, PasswordResetRequest
from django.utils.timezone import now
from django.utils.translation import gettext_lazy as _

class UserLoginSerializer(serializers.Serializer):
    username = serializers.CharField()
    password = serializers.CharField()
    role = serializers.IntegerField(min_value=1, max_value=3)  # 确保与模型定义一致

    def validate_role(self, value):
        if value not in [1, 2, 3]:  # 验证角色值
            raise serializers.ValidationError("无效的角色类型")
        return value
class UserRegisterSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True, style={'input_type': 'password'})

    class Meta:
        model = User
        fields = ['username', 'password', 'phone', 'real_name', 'email', 'role']
        extra_kwargs = {
            'password': {'write_only': True},
            'role': {'default': 'user'}
        }

    def validate_username(self, value):
        if User.objects.filter(username=value).exists():
            raise serializers.ValidationError("用户名已存在")
        return value


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id', 'username', 'email', 'role']
        read_only_fields = ['id']

class PasswordResetRequestSerializer(serializers.ModelSerializer):
    user = UserSerializer(read_only=True)

    class Meta:
        model = PasswordResetRequest
        fields = ['id', 'user', 'created_at', 'is_processed']
        read_only_fields = ['id', 'user', 'created_at', 'is_processed']

class RequestPasswordResetSerializer(serializers.Serializer):
    username = serializers.CharField(max_length=150)
    email = serializers.EmailField()
    role = serializers.CharField(max_length=10)

    def validate(self, data):
        try:
            user = User.objects.get(
                username=data['username'],
                email=data['email'],
                role=data['role']
            )
        except User.DoesNotExist:
            raise serializers.ValidationError(_("用户信息不匹配"))
        return data

class ProcessResetRequestSerializer(serializers.Serializer):
    request_id = serializers.IntegerField()
    default_password = serializers.CharField(default='12345678', write_only=True)

    def validate_request_id(self, value):
        try:
            request = PasswordResetRequest.objects.get(
                id=value,
                is_processed=False
            )
        except PasswordResetRequest.DoesNotExist:
            raise serializers.ValidationError(_("无效的重置请求或已处理"))
        return value
